package com.example;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @since 内省
 */
public class TestIntrospector {


    public static class User {
        private Integer id;
        private String name;
        private String address;
        private Integer age;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", address='" + address + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    public static void main(String[] args) {
        Class clazz = User.class;
        Object object = null;
        try {
            object = clazz.newInstance();
            //通过类信息获取bean的描述
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            //根据类信息获取属性描述器
            PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                //得到写的方法
                Method writeMethod = descriptor.getWriteMethod();
                //得到属性名字
                String name = descriptor.getName();
                if ( "id".equals(name) ) {
                    writeMethod.invoke(object, 1);
                }
                else if ( "name".equals(name) ) {
                    writeMethod.invoke(object, "小玉");
                }
            }
        }
        catch (IntrospectionException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        catch (InstantiationException e) {
            e.printStackTrace();
        }
        catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println(object);
    }
}




